﻿namespace Hidistro.UI.Web.API
{
    using Hidistro.Core;
    using Hidistro.Entities;
    using Hidistro.Entities.Comments;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Entities.VShop;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.Messages;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Member;
    using Hidistro.SaleSystem.Shopping;
    using Hidistro.SaleSystem.Vshop;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Security;

    public class VshopProcess : IHttpHandler
    {
        private void AddFavorite(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"请先登录才可以收藏商品\"}");
            }
            else if (ProductBrowser.AddProductToFavorite(Convert.ToInt32(context.Request["ProductId"]), user.UserId))
            {
                context.Response.Write("{\"success\":true}");
            }
            else
            {
                context.Response.Write("{\"success\":false, \"msg\":\"提交失败\"}");
            }
        }

        private void AddProductConsultations(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            ProductConsultationInfo productConsultation = new ProductConsultationInfo
            {
                ConsultationDate = DateTime.Now,
                ConsultationText = context.Request["ConsultationText"],
                ProductId = Convert.ToInt32(context.Request["ProductId"]),
                UserEmail = user.Email,
                UserId = user.UserId,
                UserName = user.Username
            };
            if (ProductBrowser.InsertProductConsultation(productConsultation))
            {
                context.Response.Write("{\"success\":true}");
            }
            else
            {
                context.Response.Write("{\"success\":false, \"msg\":\"提交失败\"}");
            }
        }

        private void AddProductReview(HttpContext context)
        {
            int num2;
            int num3;
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            int productId = Convert.ToInt32(context.Request["ProductId"]);
            ProductBrowser.LoadProductReview(productId, out num2, out num3);
            if (num2 == 0)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"您没有购买此商品(或此商品的订单尚未完成)，因此不能进行评论\"}");
            }
            else if (num3 >= num2)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"您已经对此商品进行过评论(或此商品的订单尚未完成)，因此不能再次进行评论\"}");
            }
            else
            {
                ProductReviewInfo review = new ProductReviewInfo
                {
                    ReviewDate = DateTime.Now,
                    ReviewText = context.Request["ReviewText"],
                    ProductId = productId,
                    UserEmail = user.Email,
                    UserId = user.UserId,
                    UserName = user.Username
                };
                if (ProductBrowser.InsertProductReview(review))
                {
                    context.Response.Write("{\"success\":true}");
                }
                else
                {
                    context.Response.Write("{\"success\":false, \"msg\":\"提交失败\"}");
                }
            }
        }

        private void AddShippingAddress(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                ShippingAddressInfo shippingAddress = new ShippingAddressInfo
                {
                    Address = context.Request.Form["address"],
                    CellPhone = context.Request.Form["cellphone"],
                    ShipTo = context.Request.Form["shipTo"],
                    Zipcode = "12345",
                    IsDefault = true,
                    UserId = user.UserId,
                    RegionId = Convert.ToInt32(context.Request.Form["regionSelectorValue"])
                };
                if (Hidistro.SaleSystem.Member.MemberProcessor.AddShippingAddress(shippingAddress) > 0)
                {
                    context.Response.Write("{\"success\":true}");
                }
                else
                {
                    context.Response.Write("{\"success\":false}");
                }
            }
        }

        private void AddSignUp(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int activityid = Convert.ToInt32(context.Request["id"]);
            string str = Convert.ToString(context.Request["code"]);
            LotteryTicketInfo lotteryTicket = VshopBrowser.GetLotteryTicket(activityid);
            if (!string.IsNullOrEmpty(lotteryTicket.InvitationCode) && (lotteryTicket.InvitationCode != str))
            {
                context.Response.Write("{\"success\":false, \"msg\":\"邀请码不正确\"}");
            }
            else if (lotteryTicket.EndTime < DateTime.Now)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"活动已结束\"}");
            }
            else if (lotteryTicket.OpenTime < DateTime.Now)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"报名已结束\"}");
            }
            else if (VshopBrowser.GetUserPrizeRecord(activityid) == null)
            {
                PrizeRecordInfo model = new PrizeRecordInfo
                {
                    ActivityID = activityid
                };
                Member user = HiContext.Current.User as Member;
                model.UserID = user.UserId;
                model.UserName = user.Username;
                model.IsPrize = true;
                model.Prizelevel = "已报名";
                model.PrizeTime = new DateTime?(DateTime.Now);
                VshopBrowser.AddPrizeRecord(model);
                context.Response.Write("{\"success\":true, \"msg\":\"报名成功\"}");
            }
            else
            {
                context.Response.Write("{\"success\":false, \"msg\":\"你已经报名了，请不要重复报名！\"}");
            }
        }

        private void AddTicket(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int activityid = Convert.ToInt32(context.Request["activityid"]);
            LotteryTicketInfo lotteryTicket = VshopBrowser.GetLotteryTicket(activityid);
            Member user = HiContext.Current.User as Member;
            if ((user != null) && !lotteryTicket.GradeIds.Contains(user.GradeId.ToString()))
            {
                context.Response.Write("{\"success\":false, \"msg\":\"您的会员等级不在此活动范内\"}");
            }
            else if (lotteryTicket.EndTime < DateTime.Now)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"活动已结束\"}");
            }
            else if (DateTime.Now < lotteryTicket.OpenTime)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"抽奖还未开始\"}");
            }
            else if (VshopBrowser.GetCountBySignUp(activityid) < lotteryTicket.MinValue)
            {
                context.Response.Write("{\"success\":false, \"msg\":\"还未达到人数下限\"}");
            }
            else
            {
                PrizeRecordInfo userPrizeRecord = VshopBrowser.GetUserPrizeRecord(activityid);
                try
                {
                    if (!lotteryTicket.IsOpened)
                    {
                        VshopBrowser.OpenTicket(activityid);
                        userPrizeRecord = VshopBrowser.GetUserPrizeRecord(activityid);
                    }
                    else if (!string.IsNullOrWhiteSpace(userPrizeRecord.RealName) && !string.IsNullOrWhiteSpace(userPrizeRecord.CellPhone))
                    {
                        context.Response.Write("{\"success\":false, \"msg\":\"您已经抽过奖了\"}");
                        return;
                    }
                    if ((userPrizeRecord == null) || string.IsNullOrEmpty(userPrizeRecord.PrizeName))
                    {
                        context.Response.Write("{\"success\":false, \"msg\":\"很可惜,你未中奖\"}");
                        return;
                    }
                    if (!userPrizeRecord.PrizeTime.HasValue)
                    {
                        userPrizeRecord.PrizeTime = new DateTime?(DateTime.Now);
                        VshopBrowser.UpdatePrizeRecord(userPrizeRecord);
                    }
                }
                catch (Exception exception)
                {
                    context.Response.Write("{\"success\":false, \"msg\":\"" + exception.Message + "\"}");
                    return;
                }
                context.Response.Write("{\"success\":true, \"msg\":\"恭喜你获得" + userPrizeRecord.Prizelevel + "\"}");
            }
        }

        private void AddUserPrize(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int result = 1;
            int.TryParse(context.Request["activityid"], out result);
            string str = context.Request["prize"];
            LotteryActivityInfo lotteryActivity = VshopBrowser.GetLotteryActivity(result);
            PrizeRecordInfo model = new PrizeRecordInfo
            {
                PrizeTime = new DateTime?(DateTime.Now),
                UserID = HiContext.Current.User.UserId,
                ActivityName = lotteryActivity.ActivityName,
                ActivityID = result,
                Prizelevel = str
            };
            switch (str)
            {
                case "一等奖":
                    model.PrizeName = lotteryActivity.PrizeSettingList[0].PrizeName;
                    model.IsPrize = true;
                    break;

                case "二等奖":
                    model.PrizeName = model.PrizeName = lotteryActivity.PrizeSettingList[1].PrizeName;
                    model.IsPrize = true;
                    break;

                case "三等奖":
                    model.PrizeName = lotteryActivity.PrizeSettingList[2].PrizeName;
                    model.IsPrize = true;
                    break;

                case "四等奖":
                    model.PrizeName = lotteryActivity.PrizeSettingList[3].PrizeName;
                    model.IsPrize = true;
                    break;

                case "五等奖":
                    model.PrizeName = lotteryActivity.PrizeSettingList[4].PrizeName;
                    model.IsPrize = true;
                    break;

                case "六等奖":
                    model.PrizeName = lotteryActivity.PrizeSettingList[5].PrizeName;
                    model.IsPrize = true;
                    break;

                default:
                    model.IsPrize = false;
                    break;
            }
            VshopBrowser.AddPrizeRecord(model);
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            builder.Append("\"Status\":\"OK\"");
            builder.Append("}");
            context.Response.Write(builder);
        }

        public void BindUser(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string str = context.Request["openId"];
            string username = context.Request["userName"];
            string str3 = context.Request["password"];
            Member member = Users.GetUser(0, username, false, true) as Member;
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            if ((member == null) || member.IsAnonymous)
            {
                builder.Append("\"Status\":\"-1\"");
                builder.Append("}");
                context.Response.Write(builder.ToString());
            }
            else
            {
                member.Password = str3;
                LoginUserStatus status = Hidistro.SaleSystem.Member.MemberProcessor.ValidLogin(member);
                if (status == LoginUserStatus.Success)
                {
                    HttpCookie cookie = new HttpCookie("Vshop-Member")
                    {
                        Value = Globals.UrlEncode(username),
                        Expires = DateTime.Now.AddYears(1)
                    };
                    HttpContext.Current.Response.Cookies.Add(cookie);
                    if (!string.IsNullOrEmpty(str))
                    {
                        if (context.Request["client"] == "alioh")
                        {
                            member.AliOpenId = str;
                        }
                        else
                        {
                            member.OpenId = str;
                        }
                        Users.UpdateUser(member);
                    }

                    builder.Append("\"Status\":\"OK\"");
                    if (!string.IsNullOrEmpty(context.Request["returnUrl"]))
                    {
                        builder.AppendFormat(",\"returnUrl\":\"{0}\"", context.Request.QueryString["returnUrl"].ToString());
                    }
                }
                else
                {
                    builder.Append("\"Status\":\"" + ((int)status) + "\"");
                }
                builder.Append("}");
                context.Response.Write(builder.ToString());
            }
        }

        private void CheckFavorite(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            if (!(HiContext.Current.User is Member))
            {
                context.Response.Write("{\"success\":false}");
            }
            else if (ProductBrowser.GetProductSimpleInfo(Convert.ToInt32(context.Request["ProductId"])) != null)
            {
                context.Response.Write("{\"success\":true}");
            }
            else
            {
                context.Response.Write("{\"success\":false}");
            }
        }

        private void DelFavorite(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            if (ProductBrowser.DeleteFavorite(Convert.ToInt32(context.Request["favoriteId"])) == 1)
            {
                context.Response.Write("{\"success\":true}");
            }
            else
            {
                context.Response.Write("{\"success\":false, \"msg\":\"取消失败\"}");
            }
        }

        private void DelShippingAddress(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                int userId = user.UserId;
                if (Hidistro.SaleSystem.Member.MemberProcessor.DelShippingAddress(Convert.ToInt32(context.Request.Form["shippingid"]), userId))
                {
                    context.Response.Write("{\"success\":true}");
                }
                else
                {
                    context.Response.Write("{\"success\":false}");
                }
            }
        }

        private void FinishOrder(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            OrderInfo orderInfo = ShoppingProcessor.GetOrderInfo(Convert.ToString(context.Request["orderId"]));
            if ((orderInfo != null) && Hidistro.SaleSystem.Vshop.MemberProcessor.ConfirmOrderFinish(orderInfo))
            {
                context.Response.Write("{\"success\":true}");
            }
            else
            {
                context.Response.Write("{\"success\":false, \"msg\":\"订单当前状态不允许完成\"}");
            }
        }

        private string GenerateOrderId()
        {
            string str = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 7; i++)
            {
                int num = random.Next();
                str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
            }
            int v = random.Next(0, 9);
            return (DateTime.Now.ToString("yyyyMMdd") + str + v);
        }

        private void GetPrize(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int result = 1;
            int.TryParse(context.Request["activityid"], out result);
            LotteryActivityInfo lotteryActivity = VshopBrowser.GetLotteryActivity(result);
            int userPrizeCount = VshopBrowser.GetUserPrizeCount(result);
            IUser user = HiContext.Current.User;
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            if (userPrizeCount >= lotteryActivity.MaxNum)
            {
                builder.Append("\"No\":\"-1\"");
                builder.Append("}");
                context.Response.Write(builder.ToString());
            }
            else if ((DateTime.Now < lotteryActivity.StartTime) || (DateTime.Now > lotteryActivity.EndTime))
            {
                builder.Append("\"No\":\"-3\"");
                builder.Append("}");
                context.Response.Write(builder.ToString());
            }
            else
            {
                PrizeQuery page = new PrizeQuery
                {
                    ActivityId = result
                };
                List<PrizeRecordInfo> prizeList = VshopBrowser.GetPrizeList(page);
                int num3 = 0;
                int num4 = 0;
                int num5 = 0;
                int num6 = 0;
                int num7 = 0;
                int num8 = 0;
                if ((prizeList != null) && (prizeList.Count > 0))
                {
                    num3 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "一等奖");
                    num4 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "二等奖");
                    num5 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "三等奖");
                }
                PrizeRecordInfo model = new PrizeRecordInfo
                {
                    PrizeTime = new DateTime?(DateTime.Now),
                    UserID = HiContext.Current.User.UserId,
                    ActivityName = lotteryActivity.ActivityName,
                    ActivityID = result,
                    IsPrize = true
                };
                List<PrizeSetting> prizeSettingList = lotteryActivity.PrizeSettingList;
                decimal num9 = prizeSettingList[0].Probability * 100M;
                decimal num10 = prizeSettingList[1].Probability * 100M;
                decimal num11 = prizeSettingList[2].Probability * 100M;
                int num15 = new Random(Guid.NewGuid().GetHashCode()).Next(1, 0x2711);
                if (prizeSettingList.Count > 3)
                {
                    decimal num12 = prizeSettingList[3].Probability * 100M;
                    decimal num13 = prizeSettingList[4].Probability * 100M;
                    decimal num14 = prizeSettingList[5].Probability * 100M;
                    num6 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "四等奖");
                    num7 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "五等奖");
                    num8 = prizeList.Count<PrizeRecordInfo>(a => a.Prizelevel == "六等奖");
                    if ((num15 < num9) && (prizeSettingList[0].PrizeNum > num3))
                    {
                        builder.Append("\"No\":\"9\"");
                        model.Prizelevel = "一等奖";
                        model.PrizeName = prizeSettingList[0].PrizeName;
                    }
                    else if ((num15 < num10) && (prizeSettingList[1].PrizeNum > num4))
                    {
                        builder.Append("\"No\":\"11\"");
                        model.Prizelevel = "二等奖";
                        model.PrizeName = prizeSettingList[1].PrizeName;
                    }
                    else if ((num15 < num11) && (prizeSettingList[2].PrizeNum > num5))
                    {
                        builder.Append("\"No\":\"1\"");
                        model.Prizelevel = "三等奖";
                        model.PrizeName = prizeSettingList[2].PrizeName;
                    }
                    else if ((num15 < num12) && (prizeSettingList[3].PrizeNum > num6))
                    {
                        builder.Append("\"No\":\"3\"");
                        model.Prizelevel = "四等奖";
                        model.PrizeName = prizeSettingList[3].PrizeName;
                    }
                    else if ((num15 < num13) && (prizeSettingList[4].PrizeNum > num7))
                    {
                        builder.Append("\"No\":\"5\"");
                        model.Prizelevel = "五等奖";
                        model.PrizeName = prizeSettingList[4].PrizeName;
                    }
                    else if ((num15 < num14) && (prizeSettingList[5].PrizeNum > num8))
                    {
                        builder.Append("\"No\":\"7\"");
                        model.Prizelevel = "六等奖";
                        model.PrizeName = prizeSettingList[5].PrizeName;
                    }
                    else
                    {
                        model.IsPrize = false;
                        builder.Append("\"No\":\"0\"");
                    }
                }
                else if ((num15 < num9) && (prizeSettingList[0].PrizeNum > num3))
                {
                    builder.Append("\"No\":\"9\"");
                    model.Prizelevel = "一等奖";
                    model.PrizeName = prizeSettingList[0].PrizeName;
                }
                else if ((num15 < num10) && (prizeSettingList[1].PrizeNum > num4))
                {
                    builder.Append("\"No\":\"11\"");
                    model.Prizelevel = "二等奖";
                    model.PrizeName = prizeSettingList[1].PrizeName;
                }
                else if ((num15 < num11) && (prizeSettingList[2].PrizeNum > num5))
                {
                    builder.Append("\"No\":\"1\"");
                    model.Prizelevel = "三等奖";
                    model.PrizeName = prizeSettingList[2].PrizeName;
                }
                else
                {
                    model.IsPrize = false;
                    builder.Append("\"No\":\"0\"");
                }
                builder.Append("}");
                if (context.Request["activitytype"] != "scratch")
                {
                    VshopBrowser.AddPrizeRecord(model);
                }
                context.Response.Write(builder.ToString());
            }
        }

        public void GetShippingTypes(HttpContext context)
        {
            int num2;
            int regionId = Convert.ToInt32(context.Request["regionId"]);
            int num3 = !string.IsNullOrWhiteSpace(context.Request["groupBuyId"]) ? Convert.ToInt32(context.Request["groupBuyId"]) : 0;
            bool flag = num3 > 0;
            ShoppingCartInfo shoppingCart = null;
            if (int.TryParse(context.Request["buyAmount"], out num2) && !string.IsNullOrWhiteSpace(context.Request["productSku"]))
            {
                shoppingCart = ShoppingCartProcessor.GetShoppingCart(Convert.ToString(context.Request["productSku"]), num2);
            }
            else
            {
                shoppingCart = ShoppingCartProcessor.GetShoppingCart();
            }
            IEnumerable<int> source = from item in ShoppingProcessor.GetShippingModes() select item.ModeId;
            StringBuilder builder = new StringBuilder();
            if ((source != null) && (source.Count<int>() > 0))
            {
                foreach (int num4 in source)
                {
                    ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(num4, true);
                    decimal num5 = 0M;
                    if ((shoppingCart.LineItems.Count != shoppingCart.LineItems.Count<ShoppingCartItemInfo>(a => a.IsfreeShipping)) && (!shoppingCart.IsFreightFree || flag))
                    {
                        num5 = ShoppingProcessor.CalcFreight(regionId, shoppingCart.Weight, shippingMode);
                    }
                    builder.Append(",{\"modelId\":\"" + shippingMode.ModeId.ToString() + "\",\"text\":\"" + shippingMode.Name + "： ￥" + num5.ToString("F0") + "\",\"freight\":\"" + num5.ToString("F0") + "\"}");
                }
                if (builder.Length > 0)
                {
                    builder.Remove(0, 1);
                }
            }
            builder.Insert(0, "{\"data\":[").Append("]}");
            context.Response.ContentType = "application/json";
            context.Response.Write(builder.ToString());
        }

        private void ProcessAddToCartBySkus(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int quantity = int.Parse(context.Request["quantity"], NumberStyles.None);
            string skuId = context.Request["productSkuId"];
            ShoppingCartProcessor.AddLineItem(skuId, quantity);
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart();
            if (shoppingCart != null)
            {
                context.Response.Write("{\"Status\":\"OK\",\"TotalMoney\":\"" + shoppingCart.GetTotal().ToString(".00") + "\",\"Quantity\":\"" + shoppingCart.GetQuantity().ToString() + "\"}");
            }
            else
            {
                context.Response.Write("{\"Status\":\"0\"}");
            }
        }

        private void ProcessChageQuantity(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string skuId = context.Request["skuId"];
            int result = 1;
            int.TryParse(context.Request["quantity"], out result);
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            int skuStock = ShoppingCartProcessor.GetSkuStock(skuId);
            if (result > skuStock)
            {
                builder.AppendFormat("\"Status\":\"{0}\"", skuStock);
                result = skuStock;
            }
            else
            {
                builder.Append("\"Status\":\"OK\",");
                ShoppingCartProcessor.UpdateLineItemQuantity(skuId, (result > 0) ? result : 1);
                builder.AppendFormat("\"TotalPrice\":\"{0}\"", ShoppingCartProcessor.GetShoppingCart().GetAmount());
            }
            builder.Append("}");
            context.Response.ContentType = "application/json";
            context.Response.Write(builder.ToString());
        }

        private void ProcessDeleteCartProduct(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string skuId = context.Request["skuId"];
            StringBuilder builder = new StringBuilder();
            ShoppingCartProcessor.RemoveLineItem(skuId);
            builder.Append("{");
            builder.Append("\"Status\":\"OK\"");
            builder.Append("}");
            context.Response.ContentType = "application/json";
            context.Response.Write(builder.ToString());
        }

        private void ProcessGetSkuByOptions(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int productId = int.Parse(context.Request["productId"], NumberStyles.None);
            string str = context.Request["options"];
            if (string.IsNullOrEmpty(str))
            {
                context.Response.Write("{\"Status\":\"0\"}");
            }
            else
            {
                if (str.EndsWith(","))
                {
                    str = str.Substring(0, str.Length - 1);
                }
                SKUItem productAndSku = ShoppingProcessor.GetProductAndSku(productId, str);
                if (productAndSku == null)
                {
                    context.Response.Write("{\"Status\":\"1\"}");
                }
                else
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{");
                    builder.Append("\"Status\":\"OK\",");
                    builder.AppendFormat("\"SkuId\":\"{0}\",", productAndSku.SkuId);
                    builder.AppendFormat("\"SKU\":\"{0}\",", productAndSku.SKU);
                    builder.AppendFormat("\"Weight\":\"{0}\",", productAndSku.Weight);
                    builder.AppendFormat("\"Stock\":\"{0}\",", productAndSku.Stock);
                    builder.AppendFormat("\"SalePrice\":\"{0}\"", productAndSku.SalePrice.ToString("F0"));
                    builder.Append("}");
                    context.Response.ContentType = "application/json";
                    context.Response.Write(builder.ToString());
                }
            }
        }

        private void CheckOldPwd(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (!user.ChangePassword(context.Request["oldpwd"], context.Request["newpwd"]))
                context.Response.Write("{\"success\":false}");
            else
                context.Response.Write("{\"success\":true}");
        }

        public void ProcessRequest(HttpContext context)
        {
            switch (context.Request["action"])
            {
                case "CheckOldPwd":
                    this.CheckOldPwd(context);
                    return;

                case "AddToCartBySkus":
                    this.ProcessAddToCartBySkus(context);
                    return;

                case "GetSkuByOptions":
                    this.ProcessGetSkuByOptions(context);
                    return;

                case "DeleteCartProduct":
                    this.ProcessDeleteCartProduct(context);
                    return;

                case "ChageQuantity":
                    this.ProcessChageQuantity(context);
                    return;

                case "Submmitorder":
                    this.ProcessSubmmitorder(context);
                    return;

                case "AddShippingAddress":
                    this.AddShippingAddress(context);
                    return;

                case "DelShippingAddress":
                    this.DelShippingAddress(context);
                    return;

                case "SetDefaultShippingAddress":
                    this.SetDefaultShippingAddress(context);
                    return;

                case "UpdateShippingAddress":
                    this.UpdateShippingAddress(context);
                    return;

                case "GetPrize":
                    this.GetPrize(context);
                    return;

                case "SubmitActivity":
                    this.SubmitActivity(context);
                    return;

                case "AddSignUp":
                    this.AddSignUp(context);
                    return;

                case "AddTicket":
                    this.AddTicket(context);
                    return;

                case "FinishOrder":
                    this.FinishOrder(context);
                    return;

                case "AddUserPrize":
                    this.AddUserPrize(context);
                    return;

                case "SubmitWinnerInfo":
                    this.SubmitWinnerInfo(context);
                    return;

                case "SetUserName":
                    this.SetUserName(context);
                    return;

                case "BindUser":
                    this.BindUser(context);
                    return;

                case "RegisterUser":
                    this.RegisterUser(context);
                    return;

                case "AddProductConsultations":
                    this.AddProductConsultations(context);
                    return;

                case "AddProductReview":
                    this.AddProductReview(context);
                    return;

                case "AddFavorite":
                    this.AddFavorite(context);
                    return;

                case "DelFavorite":
                    this.DelFavorite(context);
                    return;

                case "CheckFavorite":
                    this.CheckFavorite(context);
                    return;

                case "Logistic":
                    this.SearchExpressData(context);
                    return;

                case "GetShippingTypes":
                    this.GetShippingTypes(context);
                    return;
            }
        }

        private void ProcessSubmmitorder(HttpContext context)
        {
            int num4;
            int num5;
            context.Response.ContentType = "application/json";
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            int result = 0;
            int num2 = 0;
            int shippingId =-1;
            if(context.Request["shippingId"]!="")
            {
               shippingId= int.Parse(context.Request["shippingId"]);
            }
          
            OrderSource source = (OrderSource)int.Parse(context.Request["orderSource"]);
            string str = context.Request["couponCode"];
            bool flag = int.TryParse(context.Request["groupbuyId"], out num4);
            string str3 = context.Request["remark"];
            ShoppingCartInfo shoppingCart = null;
            string str4 = "";
            if (!string.IsNullOrEmpty(context.Request["from"]))
            {
                str4 = context.Request["from"].ToString().ToLower();
            }
            if ((int.TryParse(context.Request["buyAmount"], out num5) && !string.IsNullOrEmpty(context.Request["productSku"])) && ((str4 == "signbuy") || (str4 == "groupbuy")))
            {
                string productSkuId = context.Request["productSku"];
                if (str4 == "signbuy")
                {
                    shoppingCart = ShoppingCartProcessor.GetShoppingCart(productSkuId, num5);
                }
                else
                {
                    shoppingCart = ShoppingCartProcessor.GetGroupBuyShoppingCart(productSkuId, num5);
                }
            }
            else
            {
                shoppingCart = ShoppingCartProcessor.GetShoppingCart();
            }
            OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(shoppingCart, false, false, false);
            if (orderInfo == null)
            {
                builder.Append("\"Status\":\"None\"");
                goto Label_0591;
            }
            orderInfo.OrderId = this.GenerateOrderId();
            orderInfo.OrderDate = DateTime.Now;
            orderInfo.OrderSource = source;
            if (shippingId == -1)
            {
                orderInfo.UserId = HiContext.Current.User.UserId;
                orderInfo.Username = HiContext.Current.User.Username;
                orderInfo.EmailAddress = HiContext.Current.User.Email;
                orderInfo.RealName = HiContext.Current.User.Username;
            }
            else
            {
                Member user = HiContext.Current.User as Member;
                orderInfo.UserId = user.UserId;
                orderInfo.Username = user.Username;
                orderInfo.EmailAddress = user.Email;
                orderInfo.RealName = user.RealName;
                orderInfo.QQ = user.QQ;
            }
            orderInfo.Remark = str3;
            if (flag)
            {
                GroupBuyInfo groupBuy = ProductBrowser.GetGroupBuy(num4);
                orderInfo.GroupBuyId = num4;
                orderInfo.NeedPrice = groupBuy.NeedPrice;
                orderInfo.GroupBuyStatus = groupBuy.Status;
            }
            orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
            orderInfo.RefundStatus = RefundStatus.None;
            orderInfo.ShipToDate = context.Request["shiptoDate"];
            if (shippingId == -1)
            {
                string[] arr = context.Request["UserInfo"].ToString().Split('|');
                orderInfo.ShippingRegion = RegionHelper.GetFullRegion(int.Parse(arr[3]), "，");
                orderInfo.RegionId = int.Parse(arr[3]);
                orderInfo.Address = arr[1];
                orderInfo.ZipCode = "000000";
                orderInfo.ShipTo = arr[0];
                orderInfo.CellPhone = arr[2];
            }
            ShippingAddressInfo shippingAddress = Hidistro.SaleSystem.Member.MemberProcessor.GetShippingAddress(shippingId);
            if (shippingAddress != null)
            {
                orderInfo.ShippingRegion = RegionHelper.GetFullRegion(shippingAddress.RegionId, "，");
                orderInfo.RegionId = shippingAddress.RegionId;
                orderInfo.Address = shippingAddress.Address;
                orderInfo.ZipCode = shippingAddress.Zipcode;
                orderInfo.ShipTo = shippingAddress.ShipTo;
                orderInfo.TelPhone = shippingAddress.TelPhone;
                orderInfo.CellPhone = shippingAddress.CellPhone;
                Hidistro.SaleSystem.Member.MemberProcessor.SetDefaultShippingAddress(shippingId, HiContext.Current.User.UserId);
            }
            if (int.TryParse(context.Request["shippingType"], out result))
            {
                ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(result, true);
                if (shippingMode != null)
                {
                    orderInfo.ShippingModeId = shippingMode.ModeId;
                    orderInfo.ModeName = shippingMode.Name;
                    if ((shoppingCart.LineItems.Count != shoppingCart.LineItems.Count<ShoppingCartItemInfo>(a => a.IsfreeShipping)) && !shoppingCart.IsFreightFree)
                    {
                        orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, shoppingCart.Weight, shippingMode);
                    }
                    else
                    {
                        orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
                    }
                }
            }
            if (int.TryParse(context.Request["paymentType"], out num2))
            {
                orderInfo.PaymentTypeId = num2;
                switch (num2)
                {
                    case 0:
                        orderInfo.PaymentType = "货到付款";
                        orderInfo.Gateway = "hishop.plugins.payment.podrequest";
                        goto Label_04BE;

                    case -2:
                        orderInfo.PaymentType = "微信支付";
                        orderInfo.Gateway = "hishop.plugins.payment.weixinrequest";
                        goto Label_04BE;

                    case -1:
                        orderInfo.PaymentType = "线下付款";
                        orderInfo.Gateway = "hishop.plugins.payment.bankrequest";
                        goto Label_04BE;

                    case -3:
                        orderInfo.PaymentType = "支付宝手机应用内支付";
                        orderInfo.Gateway = "hishop.plugins.payment.ws_apppay.wswappayrequest";
                        goto Label_04BE;

                    case -4:
                        orderInfo.PaymentType = "支付宝手机网页支付";
                        orderInfo.Gateway = "hishop.plugins.payment.ws_wappay.wswappayrequest";
                        goto Label_04BE;

                    case -5:
                        orderInfo.PaymentType = "盛付通手机网页支付";
                        orderInfo.Gateway = "Hishop.Plugins.Payment.ShengPayMobile.ShengPayMobileRequest";
                        goto Label_04BE;
                }
                PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(num2);
                if (paymentMode != null)
                {
                    orderInfo.PaymentTypeId = paymentMode.ModeId;
                    orderInfo.PaymentType = paymentMode.Name;
                    orderInfo.Gateway = paymentMode.Gateway;
                }
            }
        Label_04BE:
            if (!string.IsNullOrEmpty(str))
            {
                CouponInfo info7 = ShoppingProcessor.UseCoupon(shoppingCart.GetTotal(), str);
                orderInfo.CouponName = info7.Name;
                if (info7.Amount.HasValue)
                {
                    orderInfo.CouponAmount = info7.Amount.Value;
                }
                orderInfo.CouponCode = str;
                orderInfo.CouponValue = info7.DiscountValue;
            }
            try
            {
                if (ShoppingProcessor.CreatOrder(orderInfo))
                {
                    ShoppingCartProcessor.ClearShoppingCart();
                    builder.Append("\"Status\":\"OK\",");
                    builder.AppendFormat("\"OrderId\":\"{0}\"", orderInfo.OrderId);
                }
                else
                {
                    builder.Append("\"Status\":\"Error\"");
                }
            }
            catch (OrderException exception)
            {
                builder.Append("\"Status\":\"Error\"");
                builder.AppendFormat(",\"ErrorMsg\":\"{0}\"", exception.Message);
            }
        Label_0591:
            builder.Append("}");
            context.Response.ContentType = "application/json";
            context.Response.Write(builder.ToString());
        }

        public void RegisterUser(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string str = context.Request["openId"];
            string urlToEncode = context.Request["userName"];
            string str3 = context.Request["email"];
            string createPassword = context.Request["password"];
            Member member = new Member(UserRole.Member)
            {
                GradeId = Hidistro.SaleSystem.Member.MemberProcessor.GetDefaultMemberGrade()
            };
            if (context.Request["client"] == "alioh")
            {
                member.AliOpenId = str;
            }
            else
            {
                member.OpenId = str;
            }
            member.Username = urlToEncode;
            member.Email = str3;
            member.Password = createPassword;
            member.PasswordFormat = MembershipPasswordFormat.Hashed;
            member.TradePasswordFormat = MembershipPasswordFormat.Hashed;
            member.TradePassword = createPassword;
            member.IsApproved = true;
            member.RealName = string.Empty;
            member.Address = string.Empty;
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            switch (Hidistro.SaleSystem.Member.MemberProcessor.CreateMember(member))
            {
                case CreateUserStatus.DuplicateUsername:
                case CreateUserStatus.DisallowedUsername:
                    builder.Append("\"Status\":\"-1\"");
                    break;

                case CreateUserStatus.DuplicateEmailAddress:
                    builder.Append("\"Status\":\"-2\"");
                    break;

                case CreateUserStatus.Created:
                    {
                        Messenger.UserRegister(member, createPassword);
                        member.OnRegister(new UserEventArgs(member.Username, createPassword, null));
                        HttpCookie cookie = new HttpCookie("Vshop-Member")
                        {
                            Value = Globals.UrlEncode(urlToEncode),
                            Expires = DateTime.Now.AddYears(1)
                        };
                        HttpContext.Current.Response.Cookies.Add(cookie);
                        builder.Append("\"Status\":\"OK\"");
                        break;
                    }
                default:
                    builder.Append("\"Status\":\"0\"");
                    break;
            }
            builder.Append("}");
            context.Response.Write(builder.ToString());
        }

        private void SearchExpressData(HttpContext context)
        {
            string s = string.Empty;
            if (!string.IsNullOrEmpty(context.Request["OrderId"]))
            {
                string orderId = context.Request["OrderId"];
                OrderInfo orderInfo = ShoppingProcessor.GetOrderInfo(orderId);
                if (((orderInfo != null) && ((orderInfo.OrderStatus == OrderStatus.SellerAlreadySent) || (orderInfo.OrderStatus == OrderStatus.Finished))) && !string.IsNullOrEmpty(orderInfo.ExpressCompanyAbb))
                {
                    s = Express.GetExpressData(orderInfo.ExpressCompanyAbb, orderInfo.ShipOrderNumber);
                }
                else
                {
                    s = "商品正在出库";
                }
            }
            context.Response.ContentType = "application/json";
            context.Response.Write(s);
            context.Response.End();
        }

        private void SetDefaultShippingAddress(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                int userId = user.UserId;
                if (Hidistro.SaleSystem.Member.MemberProcessor.SetDefaultShippingAddress(Convert.ToInt32(context.Request.Form["shippingid"]), userId))
                {
                    context.Response.Write("{\"success\":true}");
                }
                else
                {
                    context.Response.Write("{\"success\":false}");
                }
            }
        }

        public void SetUserName(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            user.Username = context.Request["userName"];
            user.CellPhone = context.Request["CellPhone"];
            user.QQ = context.Request["QQ"];
            if (string.IsNullOrWhiteSpace(user.Email))
            {
                user.Email = user.QQ + "@qq.com";
            }
            user.RealName = context.Request["RealName"];
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            if (Users.UpdateUser(user))
            {
                builder.Append("\"Status\":\"OK\"");
            }
            else
            {
                builder.Append("\"Status\":\"Error\"");
            }
            builder.Append("}");
            context.Response.Write(builder.ToString());
        }

        private void SubmitActivity(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                ActivityInfo activity = VshopBrowser.GetActivity(Convert.ToInt32(context.Request.Form.Get("id")));
                if ((DateTime.Now < activity.StartDate) || (DateTime.Now > activity.EndDate))
                {
                    context.Response.Write("{\"success\":false, \"msg\":\"报名还未开始或已结束\"}");
                }
                else
                {
                    ActivitySignUpInfo info = new ActivitySignUpInfo
                    {
                        ActivityId = Convert.ToInt32(context.Request.Form.Get("id")),
                        Item1 = context.Request.Form.Get("item1"),
                        Item2 = context.Request.Form.Get("item2"),
                        Item3 = context.Request.Form.Get("item3"),
                        Item4 = context.Request.Form.Get("item4"),
                        Item5 = context.Request.Form.Get("item5"),
                        RealName = user.RealName,
                        SignUpDate = DateTime.Now,
                        UserId = user.UserId,
                        UserName = user.Username
                    };
                    string s = VshopBrowser.SaveActivitySignUp(info) ? "{\"success\":true}" : "{\"success\":false, \"msg\":\"你已经报过名了,请勿重复报名\"}";
                    context.Response.Write(s);
                }
            }
        }

        private void SubmitWinnerInfo(HttpContext context)
        {
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                int activityId = Convert.ToInt32(context.Request.Form.Get("id"));
                string realName = context.Request.Form.Get("name");
                string cellPhone = context.Request.Form.Get("phone");
                string s = VshopBrowser.UpdatePrizeRecord(activityId, user.UserId, realName, cellPhone) ? "{\"success\":true}" : "{\"success\":false}";
                context.Response.ContentType = "application/json";
                context.Response.Write(s);
            }
        }

        private void UpdateShippingAddress(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            Member user = HiContext.Current.User as Member;
            if (user == null)
            {
                context.Response.Write("{\"success\":false}");
            }
            else
            {
                ShippingAddressInfo shippingAddress = new ShippingAddressInfo
                {
                    Address = context.Request.Form["address"],
                    CellPhone = context.Request.Form["cellphone"],
                    ShipTo = context.Request.Form["shipTo"],
                    Zipcode = "12345",
                    UserId = user.UserId,
                    ShippingId = Convert.ToInt32(context.Request.Form["shippingid"]),
                    RegionId = Convert.ToInt32(context.Request.Form["regionSelectorValue"])
                };
                if (Hidistro.SaleSystem.Member.MemberProcessor.UpdateShippingAddress(shippingAddress))
                {
                    context.Response.Write("{\"success\":true}");
                }
                else
                {
                    context.Response.Write("{\"success\":false}");
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

